<template>
  <div>
    <!-- 1. show-checkbox 显示选择框
    2. default-expand-all 默认展开
    3. check-strictly  设置true，可以关闭父子关联 -->
    <el-tree
      ref="tree"
      :data="permissionData"
      :props="{label:'name'}"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />

    <div style="text-align: right;">
      <el-button @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '../../api/permisson'
import { getRoleDetail, assignPerm } from '../../api/setting'
import { tranListToTreeData } from '../../utils/tree'
export default {
  props: {
    curId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      permissionData: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissionList()
    this.loadPermissionRoleDetail()
  },
  methods: {
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.permissionData = tranListToTreeData(res.data)
      } catch (err) {
        console.log(err)
      }
    },
    // 获取已有数据
    async loadPermissionRoleDetail() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log('getRoleDetail', res)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log(err)
      }
    },
    hCancel() {
      this.$emit('close')
    },
    async hSubmit() {
      try {
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPerm({ id: this.curId, permIds })
        console.log(res)
        this.$message.success('操作成功')
        this.$emit('close')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

